#include "pugixml/pugixml.hpp"
#include "topconn_cross_platform.hpp"
#include "topconn_exception.hpp"
#include "topconn_logutil.hpp"

#include "topconn_cfg_parser.hpp"
#include "topconn_cfg_reader.hpp"
#include "topconn_cfg_loader.hpp"

namespace topconn
{
    TopConnResource& ConnResourceLoader::LoaderResource(const string& connPath,const string& connId,TopConnResource& resource)
	{
        char sError[256] = { 0 };

		ConnResourceReader reader;
		reader.loadConfigByFile(connPath);
		if (reader.getDocument().empty())
		{
			sprintf(sError,"The configuration definition is incorrect,Please check!!");
			TLOG_ERROR(sError);
			throw ConnException(sError);
		}
		TLOG_TRACE("The communication connection resource profile was loaded succed.");

		pugi::xml_node root = reader.getDocument().child("root");
		if (root.empty())
		{
			sprintf(sError, "The configuration definition is incorrect, there is no root node, please check!!");
			TLOG_ERROR(sError);
			throw ConnException(sError);
		}
		ConnConfigParser::parseRootCfg(root, resource.getRootCfg());

		pugi::xml_node connector_node = root.find_child_by_attribute("connector","id",connId.c_str());
		if (connector_node.empty())
		{
			sprintf(sError,"The specified configuration node [%s] information was not found.", connId.c_str());
			TLOG_ERROR(sError);
			throw ConnException(sError);
		}		
		TLOG_TRACE("Get the communication node [%s] information succed.", connId.c_str());

		ConnConfigParser::parseElementAttributes(connector_node, resource.getProtocalCfg());
		string policyType = resource.getProtocalCfg().get("type");
		if (policyType.empty())
		{
			sprintf(sError, "The communication node [%s] protocol type is empty", connId.c_str());
			TLOG_ERROR(sError);
			throw ConnException(sError);
		}
		resource.getProtocalCfg().setType(policyType);
		TLOG_INFO("The communication protocol type = %s", policyType.c_str());	
		return resource;
	}  

    TopConnResource& ConnResourceLoader::LoaderResource(const string& connType,map_t resource_maps, TopConnResource& resource)
    {
        resource.getProtocalCfg().setType(connType);
		TLOG_INFO("The communication protocol type = %s", connType.c_str());	
        return resource;
    }    
}
